package net.cloudcodex.shared.dto;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;
import java.util.List;

/**
 * Result of RPC.
 * @author Thomas
 */
public class Result<T> implements Serializable {
	
	/**
	 * OK / NOK
	 */
	private boolean ok;

	/**
	 * Errors codes.
	 */
	private List<String> errors = new ArrayList<String>();
	
	/**
	 * Server timestamp. may be null. usefull to deal with deltas.
	 */
	private Date timestamp = new Date();
	
	/**
	 * Handled result of the RPC
	 */
	private T data;

	public Result() {
		
	}
	
	public Result(boolean ok, Collection<String> errors, T data) {
		this.ok = ok;
		if(errors != null) {
			this.errors.addAll(errors);
		}
		this.data = data;
	}
	
	public boolean isOk() {
		return ok;
	}

	public void setOk(boolean ok) {
		this.ok = ok;
	}

	public T getData() {
		return data;
	}

	public void setData(T data) {
		this.data = data;
	}

	public List<String> getErrors() {
		return errors;
	}

	/**
	 * @return the timestamp
	 */
	public Date getTimestamp() {
		return timestamp;
	}

	/**
	 * @param timestamp the timestamp to set
	 */
	public void setTimestamp(Date timestamp) {
		this.timestamp = timestamp;
	}
	
	/**
	 * @return <code>true</code> if errors have been registered.
	 */
	public boolean hasErrors() {
		return !errors.isEmpty();
	}
	
	/**
	 * @param code an error code or a part of one.
	 * @return <code>true</code> if the context contains this error code
	 * 		or an error code starting with it.
	 */
	public boolean hasError(String code) {
		for(String error : errors) {
			if(error.startsWith(code)) {
				return true;
			}
		}
		return false;
	}
}
